package com.transpeed.payservice.webDaoImpl;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.jdom2.JDOMException;
import org.json.JSONObject;

import com.transpeed.payservice.Utils.JsonUtils;
import com.transpeed.payservice.Utils.PayCommonUtil;
import com.transpeed.payservice.Utils.XMLUtil;
import com.transpeed.payservice.Utils.XmlFormatter;
import com.transpeed.payservice.log.InitLogger;
import com.transpeed.payservice.log.Log;
import com.transpeed.payservice.main.PostMessage;
import com.transpeed.payservice.model.WeChatCarInfo;
import com.transpeed.payservice.pay.wechat.GetWeChatQRCode;
import com.transpeed.payservice.pay.wechat.PayConfigUtil;
import com.transpeed.payservice.pay.wechat.QueryWeChatTrade;



/**
 * TODO 微信API
 * GetWeChatQRCode 用于接收上位机获取微信扫码请求
 * QueryWeChatTrade  用于接收上位机查询微信订单请求
 * ReceiveWeChatTradeInfo  用于接收支付结果微信异步回传信息
 * @author lizhi
 * @date 2017年4月25日
 * 更新日志
 * 2017年4月25日 lizhi 首次创建
 *
 */

@Path("/WeChatPayAPI")
public class WeChatPayAPI {
	@POST
	@Path("/GetWeChatQRCode")
	@Produces(MediaType.TEXT_HTML)
	
	// @Produces(MediaType.APPLICATION_JSON)
	// @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	// 本地测试
	// http://192.168.0.102:8080/TranSpeed-PayService/WeChatPayAPI/GetWeChatQRCode
	// 服务器测试
	// http://122.97.128.110:8080/TranSpeed-PayService/WeChatPayAPI/GetWeChatQRCode
	// 物联网测试服务器
	// http://192.168.254.5:8080/TranSpeed-PayService/WeChatPayAPI/GetWeChatQRCode
	
	/**
	 * @author 用于接收上位机获取微信扫码请求 important!!!
	 */
	
	public String GetWeChatQRCode(
			@FormParam("TotalAmount") String TotalAmount,
			@FormParam("CarInPlace") String CarInPlace,
			@FormParam("CarOutPlace") String CarOutPlace,
			@FormParam("CarPlate") String CarPlate,
			@FormParam("CarInTime") String CarInTime,
			@FormParam("url") String NotifyUrl

	) throws Exception {

		WeChatCarInfo ParkInfo = new WeChatCarInfo();
		ParkInfo.setTotalAmount(TotalAmount);
		ParkInfo.setCarInPlace(CarInPlace);
		ParkInfo.setCarOutPlace(CarOutPlace);
		ParkInfo.setCarPlate(CarPlate);
		ParkInfo.setCarInTime(CarInTime);
		ParkInfo.setNotifyUrl(NotifyUrl);

		InitLogger.Createfolder();

		Log.Write("收到上位机生成微信二维码请求！", "WeChat");
		Log.Write("收到上位机车辆信息为：\n" + JsonUtils.formatAsJSON(new JSONObject(ParkInfo).toString()), "WeChat");
		Log.Write("开始向WeChat传送生成二维码请求！", "WeChat");

        String Subject = "自助缴费 "+ CarPlate  + " (" + CarInPlace + ")";   // 商品名称  
		String url = GetWeChatQRCode.test_trade_precreate(TotalAmount , Subject ,NotifyUrl);
		
		Log.Write("二维码生成成功！已推送给上位机!返回信息为：" + url, "WeChat");

		return url;
	}


	/**
	 * @author 用于接收上位机查询微信订单请求
	 * @throws Exception 
	 * 
	 */

	@POST
	@Path("/QueryWeChatTrade")
	@Produces(MediaType.TEXT_HTML)
	// @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	// 本地测试
	// http://192.168.0.102:8080/TranSpeed-PayService/WeChatPayAPI/QueryWeChatTrade
	// 服务器测试
	// http://122.97.128.110:8080/TranSpeed-PayService/WeChatPayAPI/QueryWeChatTrade
	// 物联网测试服务器
	// http://192.168.254.5:8080/TranSpeed-PayService/WeChatPayAPI/QueryWeChatTrade
	public String QueryWeChatTrade(@FormParam("TradeNumber") String TradeNumber) throws Exception {

		if(TradeNumber.equals("失败"))//上位机获取订单号失败的时候会传失败参数
			return "WeChat&Failed&107";	
		
		Log.Write("收到上位机查询微信订单状态请求！ 订单号为：" + TradeNumber, "WeChat");
		
		String TradeInfo = QueryWeChatTrade.WeChat_trade_query(TradeNumber);
		String TradeStatus = "Failed";//默认初始值
		
		//SUCCESS—支付成功
		if (TradeInfo.equals("SUCCESS"))
			TradeStatus = "WeChat&Success&100";
		//REFUND—转入退款
		else if(TradeInfo.equals("REFUND"))
			TradeStatus = "WeChat&Failed&102";
		//NOTPAY—未支付
		else if(TradeInfo.equals("NOTPAY"))
			TradeStatus = "WeChat&Failed&104";
		//CLOSED—已关闭
		else if(TradeInfo.equals("CLOSED"))
			TradeStatus = "WeChat&Failed&101";
		//REVOKED—已撤销（刷卡支付）
		else if(TradeInfo.equals("REVOKED"))
			TradeStatus = "WeChat&Failed&103";
		//USERPAYING--用户支付中
		else if(TradeInfo.equals("USERPAYING"))
			TradeStatus = "WeChat&Failed&105";
		//PAYERROR--支付失败(其他原因，如银行返回失败)
		else if(TradeInfo.equals("PAYERROR"))
			TradeStatus = "WeChat&Failed&106";
		
		Log.Write("已通知上位机！微信订单查询结果为：" + TradeStatus +"订单状态：" +TradeInfo, "WeChat");
		
		return TradeStatus;
	}


	/**
	 * @author lizhi 用于接收支付结果微信异步回传信息
	 * @throws JDOMException 
	 */

	@POST
	@Path("/ReceiveWeChatTradeInfo")
	@Produces(MediaType.TEXT_HTML)
	// @Produces(MediaType.APPLICATION_JSON)
	// @Consumes(MediaType.APPLICATION_JSON)
	// 访问方法路径
	// http://122.97.128.110:8080/TranSpeed-PayService/WeChatPayAPI/ReceiveWeChatTradeInfo	
	// @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String ReceiveWeChatTradeInfo(String response) throws IOException, JDOMException {
		InitLogger.Createfolder();

		Log.Write("收到微信支付结果通知：\n" + new XmlFormatter().format(response), "WeChat");
		Log.Write("收到微信推送！", "WeChat");
	
//        Map map = XMLUtil.doXMLParse(response);  
//        String tradeinfo = (String) map.get("result_code"); // WeChat&Success&订单号
//        String notifyurl = (String) map.get("attach");
//        
//		Log.Write("此条通知的支付状态：" + tradeinfo, "WeChat");
//
//        String tradestatus = "Failed";
//		if (tradeinfo.equals("SUCCESS")) {
//			tradestatus = "WeChat&Success&" + (String) map.get("out_trade_no");
//			Log.Write("开始向上位机推送成功信息！信息为：" + tradestatus, "WeChat");
//			Log.Write("推送上位机地址为：" + notifyurl, "WeChat");
//			String info = PostMessage.WeChatPost(tradestatus,notifyurl );
//			if (info!=null && info.equals("Success"))
//				Log.Write("向上位机推送信息成功！", "WeChat");
//			else
//				Log.Write("向上位机推送信息失败！", "WeChat");
//		}
//				
//		
//        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();  
//        packageParams.put("return_code", "SUCCESS");  
//        packageParams.put("return_msg", "OK");  
//          
//        String returninfo = PayCommonUtil.getRequestXml(packageParams);  
//   
//        Log.Write("返回信息： " + returninfo, "WeChat");
//        
        
		
		
		
		
        //解析xml成map  
        Map<String, String> m = new HashMap<String, String>();  
        m = XMLUtil.doXMLParse(response);  
          
        //过滤空 设置 TreeMap  
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();        
        Iterator it = m.keySet().iterator();  
        while (it.hasNext()) {  
            String parameter = (String) it.next();  
            String parameterValue = m.get(parameter);  
              
            String v = "";  
            if(null != parameterValue) {  
                v = parameterValue.trim();  
            }  
            packageParams.put(parameter, v);  
        }  
          
        // 账号信息  
        String key = PayConfigUtil.API_KEY; // key  
        String resXml = "";
        String tradestatus = "Failed";//初始化状态参数
        //判断签名是否正确  
        if(PayCommonUtil.isTenpaySign("UTF-8", packageParams,key)) {   
            //处理业务开始   
            
            if("SUCCESS".equals(packageParams.get("result_code"))){ 
            	//支付成功  
            	String notifyurl =  (String) packageParams.get("attach");
    			tradestatus = "WeChat&Success&" + packageParams.get("out_trade_no");
    			Log.Write("开始向上位机推送成功信息！信息为：" + tradestatus, "WeChat");
    			Log.Write("推送上位机地址为：" + notifyurl, "WeChat");
    			String info = PostMessage.WeChatPost(tradestatus,notifyurl );
    			if (info!=null && info.equals("Success"))
    				Log.Write("向上位机推送信息成功！", "WeChat");
    			else
    				Log.Write("向上位机推送信息失败！", "WeChat");
            	
                String mch_id = (String)packageParams.get("mch_id");  
                String openid = (String)packageParams.get("openid");  
                String is_subscribe = (String)packageParams.get("is_subscribe");  
                String out_trade_no = (String)packageParams.get("out_trade_no");  
                String total_fee = (String)packageParams.get("total_fee");  
                  
                System.out.println("mch_id:"+mch_id);  
                System.out.println("openid:"+openid);  
                System.out.println("is_subscribe:"+is_subscribe);  
                System.out.println("out_trade_no:"+out_trade_no);  
                System.out.println("total_fee:"+total_fee);  
                   
                //////////执行自己的业务逻辑////////////////  
                  
                System.out.println("支付成功");  
                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.  
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
                  
            } else {  
                System.out.println("支付失败,错误信息：" + packageParams.get("err_code"));  
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
            }
        } else{  
            System.out.println("通知签名验证失败");  
        }  
            
		return resXml;

}	
}
